package org.example.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.example.commonapi.domain.*;
import org.example.commonapi.dto.CourseStudentDto;
import org.example.commonapi.dto.LoginInfo;
import org.example.commonapi.util.JwtUtil;
import org.example.commonapi.util.options.ChoiceOptionsService;
import org.example.commonapi.util.options.InboxService;
import org.example.course.service.*;
import org.example.course.until.CourseUntil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.example.commonapi.domain.Constants.Assignment_TYPE;

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseAssignmentsController {


    @Resource
    private CourseAssignmentsService courseAssignmentsService;

    @Resource
    private AssignmentQuestionsService assignmentQuestionsService;

    @Resource
    private StudentAssignmentAnswerService studentAssignmentAnswerService;

    @Resource
    private ChoiceOptionsService choiceOptionsService;

    @Resource
    private CourseUntil courseUntil;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private StudentAssignmentService studentAssignmentService;

    /**
     * 新增课程作业
     * @param courseAssignments
     * @return
     */
    @PostMapping("/insert/assignments")
    public R addCourseAssignments(@RequestBody CourseAssignments courseAssignments) {
        R result= CourseUntil.isCourseAssignments(courseAssignments);
        if(result!=null)return result;
        courseAssignments.setCreateTime(LocalDateTime.now());
        log.info("新增课程作业：{}", courseAssignments);
        courseAssignmentsService.save(courseAssignments);
//        增加任务到所有用户收件箱
        courseUntil.notifyAssignmentCreated(courseAssignments);
        return R.success(courseAssignments.getId());
    }

    /**
     * 删除课程作业
     * @param id
     * @return
     */
    @DeleteMapping("/delete/assignments/{id}")
    public R deleteCourseAssignments(@PathVariable("id") Long id) {
        log.info("删除课程作业：{}", id);
        courseAssignmentsService.removeById(id);
        return R.success();
    }

    /**
     * 修改课程作业
     * @param courseAssignments
     * @return
     */
    @PutMapping("/update/assignments")
    public R updateCourseAssignments(@RequestBody CourseAssignments courseAssignments) {
        R result= CourseUntil.isCourseAssignments(courseAssignments);
        if(result!=null)return result;
        log.info("修改课程作业：{}", courseAssignments);
        courseAssignmentsService.updateById(courseAssignments);
        return R.success();
    }

    /**
     * 查询课程作业信息
     * @param courseId
     * @return
     */
    @GetMapping("/list/assignments/{courseId}")
    public R listCourseAssignments(@PathVariable("courseId") Long courseId) {
        LambdaQueryWrapper<CourseAssignments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseAssignments::getCourseId, courseId);
        List<CourseAssignments> list = courseAssignmentsService.list(queryWrapper);
        log.info("查询课程作业信息：{}", list);
        return R.success(list);
    }

    /**
     * 查询所有课程作业信息
     * @return
     */
    @GetMapping("/list/allassignments")
    public R listAllCourseAssignments() {
        List<CourseAssignments> list = courseAssignmentsService.list();
        return R.success(list);
    }

    /**
     * 查询进行中课程作业信息
     * @return
     */
    @GetMapping("/list/ongoing/assignments/{courseId}")
    public R listOngoingCourseAssignments(@PathVariable("courseId") Long courseId) {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<CourseAssignments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseAssignments::getCourseId,courseId)
                .le(CourseAssignments::getStartTime, now)
                .ge(CourseAssignments::getEndTime, now);
        List<CourseAssignments> list = courseAssignmentsService.list(queryWrapper);
        log.info("查询进行中课程作业信息：{}", list);
        return R.success(list);
    }

    /**
     * 查询已结束课程作业信息
     * @return
     */
    @GetMapping("/list/end/assignments/{courseId}")
    public R listEndedCourseAssignments(@PathVariable("courseId") Long courseId) {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<CourseAssignments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseAssignments::getCourseId,courseId).lt(CourseAssignments::getEndTime, now);
        List<CourseAssignments> list = courseAssignmentsService.list(queryWrapper);
        log.info("查询已结束课程作业信息：{}", list);
        return R.success(list);
    }

    /**
     * 查看当前作业信息
     * @param id
     * @return
     */
    @GetMapping("/get/assignment/{id}")
    public R getCourseAssignments(@PathVariable("id") Long id) {
        LambdaQueryWrapper<CourseAssignments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseAssignments::getId, id);
        CourseAssignments courseAssignments = courseAssignmentsService.getOne(queryWrapper);
        return R.success(courseAssignments);
    }

    /**
     * 获取该作业所有题目
     * @param assignmentId
     * @return
     */
    @GetMapping("/list/assignment/questions/{assignmentId}")
    public R getSonChaptersTest(@PathVariable Long assignmentId){
        LambdaQueryWrapper<AssignmentQuestions> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AssignmentQuestions::getAssignmentId,assignmentId);
        List<AssignmentQuestions> assignmentQuestions=assignmentQuestionsService.list(queryWrapper);
        return R.success(assignmentQuestions);
    }


    /**
     * 获取作业题目选项
     * @param id
     * @return
     */
    @GetMapping("/get/assignment/question/options/{id}")
    public R getAssignmentQuestionOptions(@PathVariable("id") Long id){
        LambdaQueryWrapper<ChoiceOptions> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ChoiceOptions::getAssignmentQuestionId,id);
        ChoiceOptions choiceOptions=choiceOptionsService.getOne(queryWrapper);
        return R.success(choiceOptions);
    }

    /**
     * 增加作业题目
     * @param assignmentQuestionsList
     * @return
     */
    @PostMapping("/insert/list/assignment/questions/{id}")
    public R insertAssignmentQuestions(@PathVariable Long id,@RequestBody List<AssignmentQuestions> assignmentQuestionsList){
        for (AssignmentQuestions assignmentQuestions : assignmentQuestionsList) {
            assignmentQuestions.setAssignmentId(id);
        }
        assignmentQuestionsService.saveBatch(assignmentQuestionsList);
        List<Long> ids=assignmentQuestionsList.stream().map(AssignmentQuestions::getId).collect(Collectors.toList());
        return R.success(ids);
    }

    /**
     * 增加作业题目选项
     * @param choiceOptionsList
     * @return
     */
    @PostMapping("/insert/list/assignment/question/options")
    public R insertAssignmentQuestionOptions(@RequestBody List<ChoiceOptions> choiceOptionsList){
        choiceOptionsService.saveBatch(choiceOptionsList);
        return R.success();
    }

    /**
     * 课程考试提交答案(获取到id)
     * @param answer
     * @return
     */
    @PostMapping("/post/assignment/submitAnswer")
    public R<String> submitAnswer(@RequestBody List<StudentAssignmentAnswer> answer) {
        studentAssignmentAnswerService.saveBatch(answer);
        return R.success();
    }


    /**
     * 学生课程作业提交(返回给前端id)
     * @param assignmentId
     * @param request
     * @return
     */
    @PostMapping("/submit/assignment/{assignmentId}")
    public R submitExams(@PathVariable Long assignmentId, HttpServletRequest request) {
        LoginInfo loginInfo = jwtUtil.parseJwt(request.getHeader("token"));
        StudentAssignment studentAssignment=new StudentAssignment();
        studentAssignment.setUserId(loginInfo.getId());
        studentAssignment.setAssignmentId(assignmentId);
        studentAssignmentService.save(studentAssignment);
        long studentAssignmentId=studentAssignment.getId();
        return R.success(studentAssignmentId);
    }


    /**
     * 查询学生是否已经提交过作业
     * @param assignmentId
     * @param request
     * @return
     */
    @GetMapping("/get/assignment/finish/{assignmentId}")
    public R getAssignmentFinish(@PathVariable Long assignmentId, HttpServletRequest request) {
        LoginInfo loginInfo = jwtUtil.parseJwt(request.getHeader("token"));
        LambdaQueryWrapper<StudentAssignment> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentAssignment::getUserId,loginInfo.getId());
        queryWrapper.eq(StudentAssignment::getAssignmentId,assignmentId);
        StudentAssignment studentAssignment=studentAssignmentService.getOne(queryWrapper);
        return R.success(studentAssignment);
    }

    /**
     * 返回学生作业答案
     * @param assignmentId
     * @param request
     * @return
     */
    @GetMapping("/list/assignment/student/answer/{assignmentId}")
    public R getAssignmentStudentAnswer(@PathVariable Long assignmentId,HttpServletRequest request){
        LoginInfo loginInfo = jwtUtil.parseJwt(request.getHeader("token"));
//      查询学生作业完成记录id
        LambdaQueryWrapper<StudentAssignment> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentAssignment::getUserId,loginInfo.getId()).eq(StudentAssignment::getId,assignmentId);
        StudentAssignment studentAssignment=studentAssignmentService.getOne(queryWrapper);
//        查询学生对作业的答案
        LambdaQueryWrapper<StudentAssignmentAnswer> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(StudentAssignmentAnswer::getStudentAssignmentId,studentAssignment.getId());
        List<StudentAssignmentAnswer> studentAssignmentAnswers=studentAssignmentAnswerService.list(queryWrapper1);
        return R.success(studentAssignmentAnswers);
    }


}
